package com.flyco.modules.data;

import com.flyco.common.api.vo.Result;
import com.flyco.common.util.ImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.iherus.codegen.qrcode.QrcodeGenerator;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

@Api(tags = "系统数据")
@RestController
@RequestMapping("/f/data")
@Slf4j
public class DataController {

    /**
     * 省市区
     */
    @ApiOperation(value = "省市区", notes = "省市区")
    @GetMapping(value = "/area")
    public String area() {
        String data = readJson("classpath:com/flyco/modules/data/json/area_mini.json");

        return data;

    }

    /**
     * 读取json格式文件
     *
     * @param jsonSrc
     * @return
     */
    private String readJson(String jsonSrc) {
        String json = "";
        try {
            //File jsonFile = ResourceUtils.getFile(jsonSrc);
            //json = FileUtils.re.readFileToString(jsonFile);
            //换个写法，解决springboot读取jar包中文件的问题
            InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonSrc.replace("classpath:", ""));
            json = IOUtils.toString(stream);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return json;
    }


    /**
     * 生成二维码
     */
    @ApiOperation(value = "生成二维码", notes = "生成二维码")
    @GetMapping(value = "/generateQrCode")
    public Result<String> generateQrCode(@RequestParam(name = "code", required = true) String code, @RequestParam(name = "logo") String logo, @RequestParam(name = "width") Integer width, @RequestParam(name = "height") Integer height) {
        Result<String> res = new Result<String>();
        if (width == null || width == 0) {
            width = 250;
        }
        if (height == null || height == 0) {
            height = 250;
        }
        QrcodeGenerator generator = new SimpleQrcodeGenerator();
        generator.getQrcodeConfig().setWidth(width).setHeight(height).setLogoBorderSize(0);
        generator.setRemoteLogo(logo);
        BufferedImage image = generator.generate(code).getImage();

        //转换成字节
        byte[] bytes = ImageUtil.imageToBytes(image, "png");
        //转换成base64串
        String base64 = Base64.getEncoder().encodeToString(bytes).trim();
        base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n

        res.setSuccess(true);
        res.setResult("data:image/jpg;base64," + base64);
        return res;
    }

}
